/**
 * 联动数据混合
 */

import { mapState } from 'vuex'
import { upperCase } from '@/utils'
export default {
  data() {
    return {
      optionList: [],
      // 判断是否是初次进入页面
      isFirst: true
    }
  },
  computed: {
    ...mapState('pageData', ['formDataList']),
    linkageList() {
      return this.element?.linkageList
    }
  },
  watch: {
    formDataList: {
      handler(val) {
        this.setOption()
      },
      deep: true,
      immediate: true
    },
    linkageList: {
      handler() {
        if (!this.isFirst) {
          // 如果联动数据有变化，证明联动执行成功
          this.$message.success('执行成功')
        }
        this.isFirst = false
        
      },
      deep: true,
      immediate: true
    }
  },
  methods: {
    // option去重
    unrepeated(data) {
      let arr = []
      data.forEach(item => {
        // console.log(JSON.stringify(item))
        if (!JSON.stringify(arr).includes(JSON.stringify(item))) {
          arr.push(item)
        }
      })
      return arr
    },
    setOption() {
      if (this.linkageList.length > 0) {
        // console.log(this.linkageList, '===linkageList===')
        let arr = []
        this.linkageList.forEach(item => {
          const { parentId } = item
          const parentData = this.formDataList.find(formItem => formItem.formId === parentId)
          const parentType = parentData.type
          const currentType = this.element.type
          const componentType = upperCase(currentType) + upperCase(parentType)
          // SelectInput类型的联动
          if (componentType === 'SelectInput') {
            const optionItem = this.selectInputOption(item, parentData)
            arr.push(...optionItem)
            // arr = Object.assign(arr, optionItem)
          } else if (componentType === 'SelectSelect') {
            // SelectSelect类型的联动
            this.SelectSelectOption(item, parentData)
          }
        })
        this.optionList = this.unrepeated(arr)
      }
    },
    /**
     * 方法执行抛错提示
     * @param {函数} fn 
     * @param {提示} msg 
     */
    trycatch(msg, fn) {
      try {
        fn()
      } catch (error) {
        this.$message.error(`${msg}有问题，执行失败`)
        throw new Error()
      }
    },

    // SelectInput类型
    selectInputOption(item, parentData) {
      // 函数时候，用于传递optionList
      let fnOptionList = {
        optionList: []
      }
      let optionList = []
      // 用于存储options
      // let { optionList } = this
      const { linkageData: { param: { type, reg, fnData, compareList }, currentValue } } = item
      const { vModel } = parentData
      const { options, optionsSource, urlData } = this.element
      // 判断是自定义的option还是通过URL获取的option
      const getOptions = optionsSource === '0' ? options : urlData?.urlOptions
      // 判断是正则、函数还是比较
      if (type === '0') {   // 正则
        if (vModel === '') {
          optionList = []
        } else {
          this.trycatch('正则', () => {
            if (eval(reg).test(vModel)) {
              optionList = currentValue.length > 0 ? getOptions?.filter(item => currentValue.includes(item.value)) : getOptions
            } else {
              optionList = []
            }
          })
        }
      } else if (type === '1') {    // 函数
        this.trycatch('函数', () => {
          let fn = new Function('_this', 'item', 'parentData', 'fnOptionList', fnData)
          fn(this, item, parentData, fnOptionList)
        })
      } else if (type === '2') {    // 比较
        const arr = compareList.map(compareItem => {
          const { compare, compareValue } = compareItem
          if (vModel !== '') {
            return `${vModel} ${compare} ${compareValue}`
          }
        })
        if (vModel !== '') {
          // const flag = eval(arr.join('&&'))
          this.trycatch('比较', () => {
            const flag = eval(arr.join('&&'))
            if (flag) {
              optionList = currentValue.length > 0 ? getOptions?.filter(item => currentValue.includes(item.value)) : getOptions
            } else {
              optionList = []
            }
          })
        }
      }

      return type === '1' ? fnOptionList.optionList : optionList

    },
    // SelectSelect类型
    SelectSelectOption(item, parentData) {
      const { linkageData: { parentValue, currentValue } } = item
      const { vModel } = parentData
      // console.log(vModel, '==vModel==')
      const { options, optionsSource, urlData } = this.element
      // 判断是自定义的option还是通过URL获取的option
      const getOptions = optionsSource === '0' ? options : urlData?.urlOptions
      // 下拉存在多选和单选，vModel是字符串或者数组
      // if (vModel) {
      //   this.optionList = currentValue.length > 0 ? getOptions?.filter(item => currentValue.includes(item.value)) : getOptions
      // }
    }
  },
}